package com.lm.selenium.service;

import com.lm.selenium.exception.CrawlerException;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;

import java.time.Duration;


@Service
@Retryable(maxAttempts = 3, backoff = @Backoff(delay = 1000))
public class CrawlerService {

    @Autowired
    private ProxyService proxyService;

    private WebDriver driver;

    public String fetchPage(String url) {
        try {
            driver.get(url);

            // 等待页面加载完成
            new WebDriverWait(driver, Duration.ofSeconds(10).getSeconds())
                    .until(d -> ((JavascriptExecutor) d)
                            .executeScript("return document.readyState")
                            .equals("complete"));

            return driver.getPageSource();

        } catch (TimeoutException e) {
            // 切换代理并重试
            System.out.println("Timeout detected. Switching proxy...");
            changeProxyAndRestart();
            throw new CrawlerException("Timeout occurred: " + url, e);
        }
    }

    private void changeProxyAndRestart() {
        try {
            if (driver != null) {
                driver.quit(); // 关闭旧的 WebDriver
            }

            String failedProxy = getProxyFromDriver();
            proxyService.markFailed(failedProxy);

            createWebDriverWithProxy(proxyService.getRandomProxy());

        } catch (Exception ex) {
            throw new RuntimeException("代理切换失败", ex);
        }
    }

    // 创建新的带代理的 WebDriver 实例
    private void createWebDriverWithProxy(String proxyStr) {
        Proxy proxy = new Proxy();
        proxy.setHttpProxy(proxyStr).setSslProxy(proxyStr);

        ChromeOptions options = new ChromeOptions();
        options.setProxy(proxy);
        options.addArguments("--headless=new");
        options.addArguments("--disable-gpu");

        driver = new ChromeDriver(options);
        System.out.println("创建新 WebDriver，使用代理: " + proxyStr);
    }

    // 从已有 driver 中尝试获取代理（如果支持）
    private String getProxyFromDriver() {
        Object proxyObj = ((ChromeDriver) driver).getCapabilities().getCapability("proxy");
        return proxyObj != null ? proxyObj.toString() : "unknown";
    }
}